<template>
  <div class="book-manage">
    <div class="page-header">
      <div class="header-title">
        <h1>图书管理</h1>
        <p>管理系统中的所有图书信息</p>
      </div>
      
      <!-- 统计卡片 -->
      <div class="stats-cards">
        <div class="stat-card total">
          <div class="stat-icon">
            <el-icon><Reading /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ pagination.total }}</div>
            <div class="stat-label">总图书</div>
          </div>
        </div>
        
        <div class="stat-card available">
          <div class="stat-icon">
            <el-icon><CircleCheck /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ books.filter(book => book.status === '0').length }}</div>
            <div class="stat-label">可借阅</div>
          </div>
        </div>
        
        <div class="stat-card categories">
          <div class="stat-icon">
            <el-icon><Grid /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ categories.length }}</div>
            <div class="stat-label">分类数</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 搜索筛选 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" inline>
        <el-form-item label="书名">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入书名"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="作者">
          <el-input
            v-model="searchForm.author"
            placeholder="请输入作者"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="分类">
          <el-select
            v-model="searchForm.categoryId"
            placeholder="请选择分类"
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="category in categories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 150px"
          >
            <el-option label="可借阅" :value="0" />
            <el-option label="已借出" :value="1" />
            <el-option label="维修中" :value="2" />
            <el-option label="已下架" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchBooks">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 图书列表 -->
    <el-card class="list-card" shadow="never">
      <template #header>
        <div class="table-header">
          <h3>图书列表 ({{ pagination.total }}本图书)</h3>
          <div class="header-actions">
            <el-button type="success" @click="exportBooks">
              <el-icon><Download /></el-icon>
              导出
            </el-button>
            <el-button type="primary" @click="showAddDialog">
              <el-icon><Plus /></el-icon>
              添加图书
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table 
        v-loading="loading" 
        :data="books" 
        stripe
        class="modern-table"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column label="封面" width="100" align="center">
          <template #default>
            <div class="book-cover">
              <el-icon><Reading /></el-icon>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="书名" min-width="180" show-overflow-tooltip />
        <el-table-column prop="author" label="作者" width="120" show-overflow-tooltip />
        <el-table-column prop="isbn" label="ISBN" width="130" />
        <el-table-column prop="categoryName" label="分类" width="100" />
        <el-table-column prop="publisher" label="出版社" width="140" show-overflow-tooltip />
        <el-table-column prop="price" label="价格" width="80" align="center">
          <template #default="{ row }">
            ¥{{ (row.price || 0).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="库存" width="100" align="center">
          <template #default="{ row }">
            <span class="stock-info">{{ row.available || 0 }}/{{ row.total || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="{ row }">
            <el-button size="small" type="primary" @click="editBook(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button size="small" type="danger" @click="deleteBook(row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑图书对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="700px"
      :close-on-click-modal="false"
      class="book-dialog"
      destroy-on-close
    >
      <el-form
        ref="bookFormRef"
        :model="bookForm"
        :rules="bookRules"
        label-width="80px"
        class="compact-form"
      >
        <!-- 基本信息 -->
        <div class="form-section">
          <h4 class="section-title">
            <el-icon><Reading /></el-icon>
            基本信息
          </h4>
          <el-row :gutter="16">
            <el-col :span="12">
              <el-form-item label="图书名称" prop="name">
                <el-input 
                  v-model="bookForm.name" 
                  placeholder="请输入图书名称"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="作者" prop="author">
                <el-input 
                  v-model="bookForm.author" 
                  placeholder="请输入作者"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="16">
            <el-col :span="12">
              <el-form-item label="ISBN" prop="isbn">
                <el-input 
                  v-model="bookForm.isbn" 
                  placeholder="请输入ISBN"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="分类" prop="categoryId">
                <el-select 
                  v-model="bookForm.categoryId" 
                  placeholder="请选择分类"
                  style="width: 100%"
                  clearable
                >
                  <el-option
                    v-for="category in categories"
                    :key="category.id"
                    :label="category.name"
                    :value="category.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 出版信息 -->
        <div class="form-section">
          <el-row :gutter="16">
            <el-col :span="12">
              <el-form-item label="出版社" prop="publisher">
                <el-input 
                  v-model="bookForm.publisher" 
                  placeholder="请输入出版社"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="出版日期" prop="publishDate">
                <el-date-picker
                  v-model="bookForm.publishDate"
                  type="date"
                  placeholder="请选择出版日期"
                  style="width: 100%"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 库存与价格 -->
        <div class="form-section">
          <h4 class="section-title">
            <el-icon><Box /></el-icon>
            库存与价格
          </h4>
          <el-row :gutter="16">
            <el-col :span="8">
              <el-form-item label="定价(¥)" prop="price">
                <el-input-number
                  v-model="bookForm.price"
                  :min="0"
                  :precision="2"
                  :step="0.1"
                  placeholder="0.00"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="总数量" prop="total">
                <el-input-number
                  v-model="bookForm.total"
                  :min="1"
                  :step="1"
                  placeholder="1"
                  style="width: 100%"
                  @change="handleTotalChange"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="可借数量" prop="available">
                <el-input-number
                  v-model="bookForm.available"
                  :min="0"
                  :max="bookForm.total || 999"
                  :step="1"
                  placeholder="1"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 其他信息 -->
        <div class="form-section">
          <el-row :gutter="16">
            <el-col :span="12">
              <el-form-item label="馆藏位置" prop="location">
                <el-input 
                  v-model="bookForm.location" 
                  placeholder="如：A区-1层"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态" prop="status">
                <el-select 
                  v-model="bookForm.status" 
                  placeholder="请选择状态"
                  style="width: 100%"
                >
                  <el-option label="可借阅" :value="0" />
                  <el-option label="已借出" :value="1" />
                  <el-option label="维修中" :value="2" />
                  <el-option label="已下架" :value="3" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-form-item label="图书描述" prop="description">
            <el-input
              v-model="bookForm.description"
              type="textarea"
              :rows="3"
              placeholder="请输入图书简介（可选）"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>
        </div>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="submitBookForm"
            :loading="submitLoading"
          >
            {{ submitLoading ? '保存中...' : '确定' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Download, Plus, Edit, Delete, Reading, Box, Document, Close, Check, CircleCheck, Grid } from '@element-plus/icons-vue'
import request from '@/utils/request'

const loading = ref(false)
const books = ref([])
const categories = ref([])
const dialogVisible = ref(false)
const bookFormRef = ref()
const submitLoading = ref(false)

const searchForm = ref({
  name: '',
  author: '',
  categoryId: null,
  status: null
})

const pagination = ref({
  current: 1,
  size: 10,
  total: 0
})

const bookForm = ref({
  id: null,
  name: '',
  author: '',
  isbn: '',
  publisher: '',
  publishDate: '',
  categoryId: null,
  price: 0,
  description: '',
  location: '',
  status: 0,
  total: 1,
  available: 1
})

const bookRules = {
  name: [{ required: true, message: '请输入图书名称', trigger: 'blur' }],
  author: [{ required: true, message: '请输入作者', trigger: 'blur' }],
  isbn: [{ required: true, message: '请输入ISBN', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择分类', trigger: 'change' }],
  total: [{ required: true, message: '请输入总数量', trigger: 'blur' }],
  available: [{ required: true, message: '请输入可借数量', trigger: 'blur' }]
}

const dialogTitle = computed(() => bookForm.value.id ? '编辑图书' : '添加图书')

// 获取图书列表
const fetchBooks = async () => {
  loading.value = true
  try {
    const params = {
      current: pagination.value.current,
      size: pagination.value.size,
      ...searchForm.value
    }

    // 移除空值参数
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })

    const response = await request.get('/books/page', { params })
    if (response.code === 200) {
      const data = response.data
      books.value = data.records || []
      pagination.value.total = data.total || 0
      
      // 匹配分类名称
      books.value.forEach(book => {
        if (book.categoryId && categories.value.length > 0) {
          const category = categories.value.find(cat => cat.id === book.categoryId)
          book.categoryName = category ? category.name : '未分类'
        } else {
          book.categoryName = '未分类'
        }
      })
    }
  } catch (error) {
    console.error('获取图书列表失败:', error)
    ElMessage.error('获取图书列表失败')
  } finally {
    loading.value = false
  }
}

// 获取分类列表
const fetchCategories = async () => {
  try {
    const response = await request.get('/categories')
    if (response.code === 200) {
      categories.value = response.data || []
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error('获取分类列表失败')
  }
}

// 状态处理函数
const getStatusType = (status) => {
  const normalizedStatus = typeof status === 'string' ? parseInt(status) : status
  switch (normalizedStatus) {
    case 0: return 'success'
    case 1: return 'warning'
    case 2: return 'info'
    case 3: return 'danger'
    default: return 'info'
  }
}

const getStatusText = (status) => {
  const normalizedStatus = typeof status === 'string' ? parseInt(status) : status
  switch (normalizedStatus) {
    case 0: return '可借阅'
    case 1: return '已借出'
    case 2: return '维修中'
    case 3: return '已下架'
    default: return '未知'
  }
}

// 搜索相关方法
const searchBooks = () => {
  pagination.value.current = 1
  fetchBooks()
}

const resetSearch = () => {
  searchForm.value = {
    name: '',
    author: '',
    categoryId: null,
    status: null
  }
  pagination.value.current = 1
  fetchBooks()
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.value.size = size
  pagination.value.current = 1
  fetchBooks()
}

const handleCurrentChange = (current) => {
  pagination.value.current = current
  fetchBooks()
}

// 对话框相关方法
const showAddDialog = () => {
  resetBookForm()
  dialogVisible.value = true
}

const resetBookForm = () => {
  bookForm.value = {
    id: null,
    name: '',
    author: '',
    isbn: '',
    publisher: '',
    publishDate: '',
    categoryId: null,
    price: 0,
    description: '',
    location: '',
    status: 0,
    total: 1,
    available: 1
  }
  if (bookFormRef.value) {
    bookFormRef.value.clearValidate()
  }
}

const editBook = (book) => {
  bookForm.value = { ...book }
  dialogVisible.value = true
}

const submitBookForm = () => {
  bookFormRef.value.validate(async (valid) => {
    if (!valid) return

    submitLoading.value = true
    try {
      const isEdit = !!bookForm.value.id
      const url = isEdit ? `/books/${bookForm.value.id}` : '/books'
      const method = isEdit ? 'put' : 'post'

      let response
      if (method === 'put') {
        response = await request.put(url, bookForm.value)
      } else {
        response = await request.post(url, bookForm.value)
      }
      
      if (response.code === 200) {
        ElMessage.success(isEdit ? '更新图书成功' : '添加图书成功')
        dialogVisible.value = false
        fetchBooks()
      } else {
        ElMessage.error(response.message || '操作失败')
      }
    } catch (error) {
      console.error('提交图书信息失败:', error)
      ElMessage.error('操作失败，请重试')
    } finally {
      submitLoading.value = false
    }
  })
}

const deleteBook = (book) => {
  ElMessageBox.confirm(
    `确定要删除图书《${book.name}》吗？此操作不可恢复。`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      const response = await request.delete(`/books/${book.id}`)
      if (response.code === 200) {
        ElMessage.success('删除图书成功')
        fetchBooks()
      } else {
        ElMessage.error(response.message || '删除失败')
      }
    } catch (error) {
      console.error('删除图书失败:', error)
      ElMessage.error('删除失败，请重试')
    }
  }).catch(() => {
    // 用户取消删除
  })
}

const exportBooks = () => {
  ElMessage.info('导出功能开发中...')
}

// 处理总数量变化
const handleTotalChange = (value) => {
  if (value < bookForm.value.available) {
    bookForm.value.available = value
  }
}

onMounted(async () => {
  await fetchCategories()
  fetchBooks()
})
</script>

<style scoped>
.book-manage {
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 24px;
}

.header-title {
  margin-bottom: 20px;
}

.header-title h1 {
  font-size: 24px;
  color: #333;
  margin: 0 0 8px 0;
  font-weight: 600;
}

.header-title p {
  color: #666;
  margin: 0;
  font-size: 14px;
}

.stats-cards {
  display: flex;
  gap: 20px;
  margin-bottom: 8px;
}

.stat-card {
  flex: 1;
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid #f0f2f5;
  display: flex;
  align-items: center;
  gap: 16px;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.stat-card.total .stat-icon {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-card.available .stat-icon {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-card.categories .stat-icon {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-icon {
  width: 56px;
  height: 56px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 24px;
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 28px;
  font-weight: 700;
  color: #333;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

.search-card {
  margin-bottom: 16px;
}

.list-card {
  margin-bottom: 24px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0;
}

.table-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.book-cover {
  width: 40px;
  height: 40px;
  background: #f0f2f5;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #8c8c8c;
  font-size: 20px;
}

.stock-info {
  font-weight: 500;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 24px;
  padding: 20px 0;
}

.dialog-footer {
  text-align: right;
}

/* 简洁的表单样式 */
.compact-form {
  max-width: 100%;
}

.form-section {
  margin-bottom: 24px;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  border-bottom: 2px solid #e4e7ed;
  padding-bottom: 8px;
}

.section-title .el-icon {
  color: #409eff;
  font-size: 18px;
}

:deep(.el-table th) {
  background-color: #fafafa !important;
}

:deep(.el-card__header) {
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.compact-form .el-form-item) {
  margin-bottom: 16px;
}

:deep(.compact-form .el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.compact-form .el-input-number) {
  width: 100%;
}

:deep(.compact-form .el-input-number .el-input__inner) {
  text-align: center;
}

:deep(.book-dialog .el-dialog__body) {
  padding: 0;
  background: #f8f9fa;
}

.dialog-content {
  padding: 24px;
  max-height: 70vh;
  overflow-y: auto;
}

/* 信息卡片样式 */
.info-card {
  margin-bottom: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border: none;
  overflow: hidden;
}

.info-card:last-child {
  margin-bottom: 0;
}

:deep(.info-card .el-card__header) {
  background: #fff;
  border-bottom: 2px solid #f0f2f5;
  padding: 16px 20px;
}

:deep(.info-card .el-card__body) {
  padding: 20px;
  background: #fff;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-icon {
  font-size: 18px;
  color: #409eff;
}

.header-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

/* 表单样式 */
.book-form :deep(.el-form-item) {
  margin-bottom: 20px;
}

.book-form :deep(.el-form-item__label) {
  font-weight: 500;
  color: #333;
  line-height: 40px;
}

.book-form :deep(.el-input__wrapper) {
  border-radius: 8px;
  box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.2s;
}

.book-form :deep(.el-input__wrapper:hover) {
  box-shadow: 0 2px 6px 0 rgba(0, 0, 0, 0.15);
}

.book-form :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

/* 价格输入样式 */
.price-input {
  position: relative;
  display: flex;
  align-items: center;
}

.currency-symbol {
  position: absolute;
  left: 12px;
  z-index: 1;
  color: #909399;
  font-size: 16px;
  font-weight: 500;
}

.price-number-input {
  width: 100%;
}

.price-number-input :deep(.el-input__wrapper) {
  padding-left: 32px;
}

/* 状态选项样式 */
.status-option {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 0;
}

.status-desc {
  font-size: 12px;
  color: #909399;
}

/* 按钮样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 20px 24px;
  background: #fff;
  border-top: 1px solid #f0f2f5;
}

.cancel-btn {
  border-radius: 8px;
  border: 1px solid #d9d9d9;
  color: #666;
  background: #fff;
  transition: all 0.2s;
}

.cancel-btn:hover {
  border-color: #409eff;
  color: #409eff;
  background: #ecf5ff;
}

.submit-btn {
  border-radius: 8px;
  background: linear-gradient(135deg, #409eff 0%, #3a8ee6 100%);
  border: none;
  transition: all 0.2s;
  box-shadow: 0 2px 6px 0 rgba(64, 158, 255, 0.3);
}

.submit-btn:hover {
  background: linear-gradient(135deg, #66b1ff 0%, #409eff 100%);
  box-shadow: 0 4px 12px 0 rgba(64, 158, 255, 0.4);
  transform: translateY(-1px);
}

/* 滚动条样式 */
.dialog-content::-webkit-scrollbar {
  width: 6px;
}

.dialog-content::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.dialog-content::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.dialog-content::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style> 